import * as THREE from 'three'

function parseCSV(
  data: string
): { point: string; x: number; y: number; z: number }[] {
  const csv = data.toString()
  const rows = csv.split('\n')

  const row_data = rows
    .filter((row) => row.trim() !== '')
    .map((row) => row.trim())
    .map((row) => row.split(','))
  // ['特征', '名义值X', '名义值Y', '名义值Z']
  // ['KN0001L', '-391.04493804', '-850.1', '502.0']

  const result = row_data.map((row) => ({
    point: row[0],
    x: parseFloat(row[1]),
    y: parseFloat(row[2]),
    z: parseFloat(row[3])
  }))
  // 移除第一行（标题行）
  result.shift()
  return result
}

export function utils_readCSV(
  filePath: string
): Promise<{ point: string; x: number; y: number; z: number }[]> {
  return new Promise((resolve, reject) => {
    const loader = new THREE.FileLoader()
    loader.load(
      filePath,
      (data) => {
        const result = parseCSV(data as string)
        resolve(result)
      },
      undefined, // 进度回调
      (error) => {
        console.error('读取CSV文件失败:', error)
        reject(error)
      }
    )
  })
}
